package leetcode.weekly.week297;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import leetcode.IDebug;
import leetcode.helper.H;

//Solution4Test
public class Solution4 implements IDebug {

	// Solution4Test
	public long distinctNames(String[] ideas) {
		Map<String, List<String>> mapsuff = new HashMap<>();
		Map<String, List<String>> mappre = new HashMap<>();
		for (int i = 0; i < ideas.length; i++) {
			String string = ideas[i];
			String pre = string.substring(0, 1);
			String suff = string.substring(1);
			List<String> suffs = mapsuff.getOrDefault(suff, new ArrayList<>());
			suffs.add(pre);
			mapsuff.put(suff, suffs);
			List<String> pres = mappre.getOrDefault(pre, new ArrayList<>());
			pres.add(suff);
			mappre.put(pre, pres);
		}
		int total = ideas.length;
		long ans = 0;
		for (int i = 0; i < ideas.length; i++) {
			String string = ideas[i];
			String pre = string.substring(0, 1);
			String suff = string.substring(1);
//			int dissuff = 0;
//			for (int j = 0; j < suffs.size(); j++) {
//				String p = suffs.get(j);
//				dissuff += mappre.get(p).size();
//			}
			int difpre = 0;
			List<String> suffs = mappre.get(pre);
			for (int j = 0; j < suffs.size(); j++) {
				String suf = suffs.get(j);
				difpre += mapsuff.get(suf).size();
			}
//			int back = mapsuff.get(suff).size() + mappre.get(pre).size() - 1;
			int ok = total - difpre;
			ans += (long) ok;
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(2, this.distinctNames(H.str2array2("[\"aaa\",\"baa\",\"caa\",\"bbb\",\"cbb\",\"dbb\"]")));
		H.compare(6, this.distinctNames(H.str2array2("[\"coffee\",\"donuts\",\"time\",\"toffee\"]")));
		H.compare(0, this.distinctNames(H.str2array2("[\"lack\",\"back\"]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution4 so = new Solution4();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
